package com.dao;



import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.bean.*;

/**
 * @author hhh
 *各种数据表共用数据操作类
 *
 *
 */
public class DataDao{
	private String table=null;
	private static SqlSessionFactory sessionFactory = null;
	
	public DataDao(){}
	
	public static SqlSessionFactory getSessionFactory() {//单例模式双重判断
		if (sessionFactory == null) {
			synchronized (DataDao.class) {
				if (sessionFactory == null) {
					String resource = "configuration.xml";
					InputStream inputStream = null;
					try {
						inputStream = Resources.getResourceAsStream(resource);
					} catch (IOException e) {
						e.printStackTrace();
					}
					sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
				}
			}
		}
		return sessionFactory;
	}
	public DataDao(String table){
		this.table=table;
	}

	public String getTable() {
		return table;
	}
	public void setTable(String table) {
		this.table = table;
	}
	public SqlObject find(String name) {//按name属性查询用户基本信息
		SqlSession session = getSessionFactory().openSession();
		SqlObject obj=null;
		String sql = "com.bean."+table+"Mapper.get"+table;
		obj=session.selectOne(sql,name);
		session.close();
		return obj;
	}

	public int update(SqlObject obj){
		SqlSession session =getSessionFactory().openSession();
		String statement="com.bean."+table+"Mapper.update"+table;
		int i=session.update(statement,obj);
		session.commit();
		session.close();
		return i;
	}

	public int add(SqlObject obj) {
		SqlSession session = getSessionFactory().openSession();
		String statement="com.bean."+table+"Mapper.add"+table;
		int i=session.insert(statement,obj);
		session.commit();
		session.close();
		return i;
	}
	
	public void delete(String name){
		SqlSession session = getSessionFactory().openSession();
		String statement="com.bean."+table+"Mapper.delete"+table;
		session.delete(statement,name);
		session.commit();
		session.close();
			
		}
	
	@SuppressWarnings("rawtypes")
	public List findAll(String reg){
		if(reg==null)
			reg="";
		SqlSession session = getSessionFactory().openSession();
		List<SqlObject> obj=null;
		String sql = "com.bean."+table+"Mapper.getAll"+table;
		obj=session.selectList(sql,reg);
		session.close();
		return obj;
	}
	@SuppressWarnings("rawtypes")
	public List findAll() {
		// TODO Auto-generated method stub
		return findAll("");
	}

}
